<template>
  <div>
    <!-- 渲染循环提示文本 -->
    <!-- $emit('searchClick',item) 传值给父亲 -->
    <van-cell @click="$emit('searchClick',item)" v-for="item in suggestions" :key="item" icon="search">
      <div slot="title" v-html="formatStr(item)"></div>
    </van-cell>
  </div>
</template>

<script>
// 引入防抖插件模块
import { debounce } from 'lodash'
import { getSearchSuggestios } from '@/api/search/index.js'
export default {
  name: 'sugges',
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      // setId: null
      // 存储建议数据列表
      suggestions: [],
      ifShow: true
    }
  },
  methods: {
    // 加载搜索建议
    async loadSearchSuggestion (val) {
      try {
        const { data: res } = await getSearchSuggestios(val)
        console.log(res)
        this.suggestions = res.data.options
      } catch (err) {
        this.$toast('获取数据失败')
      }
    },
    // 过滤数据
    formatStr (item) {
      // 定义正则规则
      const reg = RegExp(this.value, 'gi')
      // replace方法替换
      return item.replace(reg, `<span style="color:skyblue">${this.value}</span>`)
    }
  },
  computed: {},
  watch: {
    // value: {
    //   handler (val) {
    //     clearTimeout(this.setId)
    //     this.setId = setTimeout(() => {
    //       console.log(val)
    //     }, 900)
    //   }
    // }
    // value发生变化，触发
    value: {
      // debounce防抖函数
      handler: debounce(function (val) {
        // console.log('获取到了' + val)
        if (!this.ifShow) return
        this.loadSearchSuggestion(val)
      }, 900),
      deep: true,
      // 首次也会触发
      immediate: true
    }
  },
  filters: {},
  components: {},
  created () {
  },
  mounted () { },
  beforeDestroy () {
    this.ifShow = false
  }
}
</script>

<style scoped lang='less'>
</style>
